<template>
  <div class="login-container">
    <!-- 未登录状态显示登录图标 -->
    <el-button v-if="!isLoggedIn" class="login-button" @click="showQrDialog" type="primary" circle>
      <el-icon>
        <User />
      </el-icon>
    </el-button>
    <!-- 已登录状态显示用户头像 -->
    <el-dropdown v-else trigger="click">
      <el-avatar :size="40" :src="userInfo.avatar" class="user-avatar" />
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item disabled>
            <div class="user-dropdown-info">
              <span class="username">{{ userInfo.name }}</span>
            </div>
          </el-dropdown-item>
          <el-dropdown-item divided @click="logout">
            <el-icon>
              <SwitchButton />
            </el-icon>
            <span>退出登录</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 二维码登录对话框 -->
    <el-dialog v-model="qrDialogVisible" title="扫码登录" width="350px" align-center @close="stopPolling()">
      <div class="qrcode-container">
        <!-- 替换默认加载样式 -->
        <div class="qrcode-wrapper">
          <div v-if="qrLoading" class="qr-loading">
            <div class="loading-spinner"></div>
            <p class="loading-text">二维码加载中...</p>
          </div>
          <div v-else-if="qrExpired" class="qr-expired">
            <el-icon class="expired-icon">
              <WarningFilled />
            </el-icon>
            <p>二维码已过期</p>
            <el-button type="primary" @click="refreshQrCode">刷新</el-button>
          </div>
          <div v-else-if="networkError" class="qr-error">
            <el-icon class="error-icon">
              <WarningFilled />
            </el-icon>
            <p>网络连接异常</p>
            <p class="error-tip-small">请检查网络后重试</p>
            <el-button type="primary" @click="refreshQrCode">重试</el-button>
          </div>
          <template v-else>
            <!-- 使用 v-if 来控制二维码的显示 -->
            <img v-if="qrCodeInfo.ticket" :src="qrCodeUrl" alt="登录二维码" class="qr-image">
            <!-- 二维码下方提示文字 -->
            <div class="qr-tips">
              <p>请使用微信扫一扫登录</p>
              <p class="qr-tip-small" v-if="!showScanTip">二维码过期请刷新</p>
            </div>

            <!-- 扫码成功提示 -->
            <div v-if="showScanTip" class="scan-tip">
              <el-icon class="success-icon">
                <CircleCheckFilled />
              </el-icon>
              <span>扫码成功！正在登录...</span>
            </div>
          </template>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getQrCode, getToken, getUserInfo } from '../api/user.js'
import { useTokenStore } from '../stores/index'
import { useRoute } from 'vue-router'
// 导入Element Plus图标组件
import { User, SwitchButton, WarningFilled, CircleCheckFilled } from '@element-plus/icons-vue'
import { v4 as uuidv4 } from 'uuid';
// 弹窗相关状态
const qrDialogVisible = ref(false)
const qrLoading = ref(false)
const showScanTip = ref(false)
const qrExpired = ref(false)
const networkError = ref(false)
// 状态管理
const tokenStore = useTokenStore()
const route = useRoute()
const isLoggedIn = computed(() => !!tokenStore.token)
let pollingTimer = null // 用于存储定时器ID
// 检查登录状态
onMounted(() => {
  if (isLoggedIn.value) {
    // 已登录，获取用户信息
    getUserInfo().then(res => {
      if (res.data) {
        userInfo.value = {
          id: res.data.id,
          status: res.data.status,
          avatar: res.data.avatar,
          name: res.data.name,
          ipInfo: res.data.ipInfo,
        }
      }else{
        ElMessage.error("token无效,请重新登录")
      }
    })
  }
})
const qrCodeUrl = computed(() => {
  return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + qrCodeInfo.value.ticket
})


// 用户信息
const userInfo = ref({})
// 二维码信息
const qrCodeInfo = ref({
  "ticket": undefined,
  "expireSeconds": undefined,
  "url": undefined
})

// 显示弹窗
const showQrDialog = () => {
  qrDialogVisible.value = true
  showScanTip.value = false
  qrExpired.value = false
  networkError.value = false
  qrLoading.value = true // 设置加载状态为 true
  // 未登录，获取二维码 要生成一个uuid
  let uuid = uuidv4();;
  getQrCode(uuid).then(res => {
    qrCodeInfo.value = res.data
    Countdown(qrCodeInfo.value.expireSeconds)
    // Countdown(5)
    qrLoading.value = false // 加载完成后设置为 false
  }).catch(err => {
    console.error('获取二维码出错:', err)
    ElMessage.error('二维码获取失败，请稍后重试')
    qrLoading.value = false
    networkError.value = true // 设置为网络错误状态
  })
  pollingCheckQrCode(uuid)
}


const pollingCheckQrCode = (uuid) => {
  // 避免重复开启多个轮询
  if (pollingTimer) return
  pollingTimer = setInterval(() => {
    getToken(uuid).then(res => {
      if (res.data && res.code == 200) {
        // 登录成功，关闭弹窗
        qrDialogVisible.value = false
        // 保存 token
        tokenStore.setToken(res.data.token)
        // 更新用户信息
        userInfo.value = {
          id: res.data.id,
          status: res.data.status,
          avatar: res.data.avatar,
          name: res.data.name,
          ipInfo: res.data.ipInfo,
        }
        // 清除轮询定时器
        clearInterval(pollingTimer)
        pollingTimer = null
        // 登录成功提示
        ElMessage.success('登录成功')
        // 跳转到首页
        window.location.href = route.fullPath
      }
    }).catch(err => {
      console.error('轮询二维码状态出错:', err)
    })
  }, 3000) // 每 5 秒轮询一次
}
const stopPolling = () => {
  if (pollingTimer) {
    clearInterval(pollingTimer)
    pollingTimer = null
  }
}

// 过期时间器
const Countdown = (seconds) => {
  if (seconds <= 0) {
    qrExpired.value = true // 倒计时结束
    return
  }

  setTimeout(() => {
    Countdown(seconds - 1) // 递归调用，传递新的值
  }, 1000)
}

// 刷新二维码
const refreshQrCode = () => {
  qrLoading.value = true
  qrExpired.value = false
  networkError.value = false
  let uuid = uuidv4();
  getQrCode(uuid).then(res => {
    qrCodeInfo.value = res.data
    qrLoading.value = false
    Countdown(qrCodeInfo.value.expireSeconds)
    // Countdown(5)
  }).catch(err => {
    console.error('刷新二维码出错:', err)
    ElMessage.error('二维码刷新失败，请稍后重试')
    qrLoading.value = false
    networkError.value = true
  })
  pollingCheckQrCode(uuid)
}



// 退出登录
const logout = () => {
  tokenStore.removeToken()
  userInfo.value = {
  }
  ElMessage.success('已退出登录')
}

</script>

<style scoped>
.login-container {
  display: flex;
  align-items: center;
}

.login-button {
  font-size: 16px;
  transition: transform 0.2s;
}

.login-button:hover {
  transform: scale(1.05);
}

.user-avatar {
  cursor: pointer;
  transition: transform 0.2s;
  border: 2px solid var(--color-primary);
}

.user-avatar:hover {
  transform: scale(1.05);
}

.user-dropdown-info {
  display: flex;
  align-items: center;
  padding: 5px 0;
}

.username {
  font-weight: 500;
  margin-left: 5px;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.qrcode-wrapper {
  width: 220px;
  padding: 20px;
  border-radius: 8px;
  background-color: white;
  text-align: center;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.qr-image {
  width: 180px;
  height: 180px;
  margin: 0 auto;
  display: block;
  cursor: pointer;
  /* 为演示目的添加 */
}

.qr-tips {
  margin-top: 15px;
  color: #606266;
}

.qr-tip-small {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.scan-tip {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #67C23A;
  font-size: 14px;
  gap: 8px;
}

.success-icon {
  font-size: 18px;
  color: #67C23A;
}

.qr-expired {
  padding: 30px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 180px;
}

.expired-icon {
  font-size: 40px;
  color: #E6A23C;
  margin-bottom: 15px;
}

.qr-error {
  padding: 30px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 180px;
}

.error-icon {
  font-size: 40px;
  color: #E6A23C;
  margin-bottom: 15px;
}

.error-tip-small {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}

.qr-loading {
  height: 220px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid rgba(64, 158, 255, 0.1);
  border-radius: 50%;
  border-top-color: var(--el-color-primary);
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 15px;
}

.loading-text {
  color: var(--el-color-primary);
  font-size: 14px;
  animation: pulse 1.5s infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0% {
    opacity: 0.6;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 0.6;
  }
}
</style>
